package com.study.opcua.thread;


import com.alibaba.fastjson.JSONObject;
import com.study.opcua.config.OpcParams;
import com.study.opcua.utils.OpcClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 执行业务的子线程
 */
@Slf4j
public class SonTread implements Runnable {

    private String name;

    private String url;

    private List<OpcParams.Params> params;

    public SonTread(String name, String url, List<OpcParams.Params> params){
        this.name = name;
        this.url = url;
        this.params = params;
    }

    @Override
    public void run() {
        // TODO 执行业务
//        System.out.println("业务开始执行了，--------" + name);
        OpcUaClient opcUaClient = OpcClientUtil.getClient(url);
        if(opcUaClient != null) {
            List<NodeId> nodeIds = new ArrayList<>();
//            List<OpcParams.Params> agv1params = opcParams.getAgv1params();
            if (params != null && params.size() > 0) {
                for (OpcParams.Params p : params) {
                    String names = p.getNames();
                    if (names != null && !"".equals(names)) {
                        String[] split = names.split(",");
                        for (String str : split) {
                            nodeIds.add(new NodeId(2, p.getPrefix() + str.trim()));
                        }
                    }
                }
            }

            // 批量读取opc参数值
            Map<NodeId, Object> map = OpcClientUtil.readValues(opcUaClient, nodeIds);

            String param = JSONObject.toJSONString(map);
            log.info("--------------读到数据--------" + name + "--------------------------:" + param);
        }
    }
}
